/**
 * 将字符串中的全角字符转换为半角字符。
 * @param {String} str 
 * @returns 
 */
function DBC2SBC(str) {
    var result = "";
    for (var i = 0; i < str.length; i++) {
        code = str.charCodeAt(i);    //获取当前字符的unicode编码
        if (code >= 65281 && code <= 65373)   //在这个unicode编码范围中的是所有的英文字母已经各种字符
        {
            var d = str.charCodeAt(i) - 65248;
            result += String.fromCharCode(d);   //把全角字符的unicode编码转换为对应半角字符的unicode码
        }
        else if (code == 12288)//空格
        {
            var d = str.charCodeAt(i) - 12288 + 32;
            result += String.fromCharCode(d);
        }
        else {
            result += str.charAt(i);
        }
    }
    return result;
}

/**
 * 去除首尾空格符
 * @param {String} str 
 * @returns 
 */
function trimStr(str) {
    return str.replace(/(^\s*)|(\s*$)/g, "");
}

var srcDataAddressX = 0
var srcDataAddressY = 0
var srcDataColumnsCount = 0
var srcDataRowsCount = 0
var srcSheetName = 0
var srcRange

var findAddressX = 0
var findAddressY = 0
var findRowsCount = 0  // 只支持一列查找
var findSheetName = 0
var findRange
var findColumnsArray = []  // 查找条件数组，内部是子组[值, 列真实索引]

var dataSourceWorkbook;
var findWorkbook;

function onbuttonclick(idStr) {
    if (typeof (wps.Enum) != "object") { // 如果没有内置枚举值
        wps.Enum = WPS_Enum
    }
    switch (idStr) {
        case "setDataSource": {
            //alert("setDataSource")
            dataSourceWorkbook = wps.EtApplication().ActiveWorkbook;
            var aSheet = dataSourceWorkbook.ActiveSheet;
            srcSheetName = aSheet.Name;
            var txtDataSource = document.getElementById("txtDataSource");
            let s = wps.Application.Selection;
            if (s.Areas.Count != 1) {
                alert("用于查找的源数据区域必须是连续的！");
                return;
            }
            var srcAddress = ("From: [" + dataSourceWorkbook.Name + "] - " + srcSheetName + "\r\nRow: " + s.Row + ", Rows Count: " + s.Rows.Count + "\r\n" +
                "Column: " + s.Column + ", Columns Count: " + s.Columns.Count);
            //alert(srcAddress)
            txtDataSource.value = srcAddress;
            srcRange = s;

            srcDataAddressY = s.Row;
            srcDataAddressX = s.Column;
            srcDataColumnsCount = s.Columns.Count;
            srcDataRowsCount = s.Rows.Count;

            break
        }
        case "setFindColumnFields": {
            //alert("setFindColumn")
            findWorkbook = wps.EtApplication().ActiveWorkbook;
            var aSheet = findWorkbook.ActiveSheet;
            findSheetName = aSheet.Name;

            var findConditionFields = document.getElementById("txtConditionFields")
            let s = wps.Application.Selection

            if (s.Rows.Count < 1 || s.Rows.Count > 1) {
                alert("用作查找条件的单元格必须在同一行内！");  // 其实根本不可能少于1行
                return;
            }

            var findConditionAddress = ("Find: [" + findWorkbook.Name + "] - " + findSheetName + "\r\nRow: " + s.Row + ", Rows Count: " + s.Rows.Count + "\r\n" +
                "Areas Count: " + s.Areas.Count);

            findColumnsArray = [];
            var areas = s.Areas;
            for (var ai = 1; ai <= areas.Count; ai++) {
                let area = areas.Item(ai);
                let cells = area.Cells;
                for (var ci = 1; ci <= cells.Count; ci++) {
                    let cell = cells.Item(ci);
                    let colArray = [];
                    colArray.push(cell.Value2);
                    colArray.push(cell.Column);
                    findColumnsArray.push(colArray);
                }
            }

            var findColumnAddress = ("Find: [" + findWorkbook.Name + "] - " + findSheetName + "\r\nRow: " + s.Row + ", Rows Count: " + s.Rows.Count + "\r\n" +
                (s.Cells.Count > 1 ? "Fields Count: " : "Field Count: ") + s.Cells.Count);
            //alert(findColumnAddress)

            var conditionTextArea = document.getElementById('txtConditionFields');
            if (conditionTextArea) {
                conditionTextArea.value = findColumnAddress;
            }

            findAddressY = s.Row;

            break
        }
        case "btnDrop": {
            if (findColumnsArray == null || findColumnsArray == undefined || findColumnsArray.length <= 0) {
                alert("未指定查找条件区域，可者指定的查找条件区域没有可用的数据！");
                return;
            }

            if (dataSourceWorkbook == undefined) {
                alert("未设置数据源表！");
                return;
            }
            if (findWorkbook == undefined) {
                alert("未设置提取条件表！");
                return;
            }
            var srcSheets = dataSourceWorkbook.Sheets;
            var srcSheet;
            for (j = 1; j <= srcSheets.Count; j++) {   // 注意：这个索引是从1开始的！！！
                var ss = srcSheets.Item(j);
                if (ss == null) continue;
                if (ss.Name == srcSheetName) {
                    srcSheet = ss;
                    break;
                }
            }
            if (srcSheet == undefined) {
                alert('未找到源数据表！');
                return;
            }
            var findSheets = findWorkbook.Sheets;
            var fndSheet;
            for (j = 1; j <= findSheets.Count; j++) {   // 注意：这个索引是从1开始的！！！
                var fs = findSheets.Item(j);
                if (fs == null) continue;
                if (fs.Name == findSheetName) {
                    fndSheet = fs;
                    break;
                }
            }
            if (fndSheet == undefined) {
                alert('未找到提取条件所在数据表！');
                return;
            }

            srcOffcet = 1;
            var fndOffcet = 1;

            // 注意:坐标是先行后列!!!不是先X后Y!!!
            var srcTitleRangeArr = srcSheet.Range(srcSheet.Cells.Item(srcDataAddressY + srcOffcet - 1, srcDataAddressX), srcSheet.Cells.Item(srcDataAddressY + srcOffcet - 1, srcDataAddressX + srcDataColumnsCount - 1)).Value2;
            if (srcTitleRangeArr.length == 1) {
                srcTitleRangeArr = srcTitleRangeArr[0];
            }
            var srcRange = srcSheet.Range(srcSheet.Cells.Item(srcDataAddressY + srcOffcet, srcDataAddressX), srcSheet.Cells.Item(srcDataAddressY + srcDataRowsCount - 1, srcDataAddressX + srcDataColumnsCount - 1));
            var srcArray = srcRange.Value2;

            if (srcDataRowsCount <= 1 || srcArray == null || srcArray == undefined || srcArray.length <= 0) {
                alert("指定的源数据区域中没有可用的数据!");
                return;
            }

            var emptyRowsCountInput = document.getElementById("iptEmptyRowsCount");
            var emptyRowsCount = parseInt(emptyRowsCountInput.value);

            wps.EtApplication.ScreenUpdating = false;  // 禁止屏幕刷新
            for (let fcai = 0; fcai < findColumnsArray.length; fcai++) {
                var conditionArr = findColumnsArray[fcai];
                var resultArray = [];
                for (let sti = 0; sti < srcTitleRangeArr.length; sti++) {
                    if (conditionArr[0] == srcTitleRangeArr[sti]) {
                        for (let si = 0; si < srcArray.length; si++) {
                            let cellValArray = srcArray[si][sti];
                            let rowValArray = [];
                            rowValArray.push(cellValArray);
                            resultArray.push(rowValArray);
                        }
                        break;
                    }
                }
                if (resultArray.length > 0) {
                    var rng = fndSheet.Range(fndSheet.Cells.Item(findAddressY + 1 + emptyRowsCount, conditionArr[1]),
                        fndSheet.Cells.Item(findAddressY + emptyRowsCount + resultArray.length, conditionArr[1]));
                    rng.NumberFormatLocal = "@";
                    rng.Value2 = resultArray;
                }
            }
            wps.EtApplication.ScreenUpdating = true;  // 禁止屏幕刷新
            break;
        }
    }
}


window.onload = () => {
    // var xmlReq = WpsInvoke.CreateXHR();
    // var url = location.origin + "/.debugTemp/NotifyDemoUrl"
    // xmlReq.open("GET", url);
    // xmlReq.onload = function (res) {
    //     var node = document.getElementById("DemoSpan");
    //     window.document.getElementById("DemoSpan").innerHTML = res.target.responseText;
    // };
    // xmlReq.send();
}